// 布局引擎相关功能实现

use super::app::FeatureTester;
use eframe::egui;

impl FeatureTester {
    // 盒模型标签页
    pub fn render_box_model_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("盒模型可视化");

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("HTML内容:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.html_input)
                        .desired_width(ui.available_width() * 0.48)
                        .desired_rows(10),
                );
            });

            ui.vertical(|ui| {
                ui.label("CSS样式:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.css_input)
                        .desired_width(ui.available_width())
                        .desired_rows(10),
                );
            });
        });

        ui.add_space(10.0);
        ui.label("选择元素 (CSS选择器):");
        ui.text_edit_singleline(&mut self.css_selector);

        ui.add_space(5.0);
        if ui.button("分析盒模型").clicked() {
            self.box_model_info = self.analyze_box_model();
        }

        ui.add_space(10.0);
        ui.label("盒模型分析结果:");
        ui.add(
            egui::TextEdit::multiline(&mut self.box_model_info)
                .desired_width(f32::INFINITY)
                .desired_rows(8)
                .frame(true)
                .interactive(false), // 修改 read_only(true) 为 interactive(false)
        );

        ui.add_space(10.0);
        ui.collapsing("盒模型可视化", |ui| {
            let (rect, _) = ui.allocate_exact_size(
                egui::vec2(ui.available_width(), 300.0),
                egui::Sense::hover(),
            );

            if !self.box_model_info.is_empty() {
                // 绘制盒模型可视化
                let margin_color = egui::Color32::from_rgb(251, 247, 200);
                let border_color = egui::Color32::from_rgb(237, 218, 157);
                let padding_color = egui::Color32::from_rgb(213, 232, 212);
                let content_color = egui::Color32::from_rgb(191, 207, 255);

                // 绘制各层
                let margin_rect = rect;
                let border_rect = egui::Rect::from_min_max(
                    egui::pos2(margin_rect.min.x + 20.0, margin_rect.min.y + 20.0),
                    egui::pos2(margin_rect.max.x - 20.0, margin_rect.max.y - 20.0),
                );
                let padding_rect = egui::Rect::from_min_max(
                    egui::pos2(border_rect.min.x + 10.0, border_rect.min.y + 10.0),
                    egui::pos2(border_rect.max.x - 10.0, border_rect.max.y - 10.0),
                );
                let content_rect = egui::Rect::from_min_max(
                    egui::pos2(padding_rect.min.x + 15.0, padding_rect.min.y + 15.0),
                    egui::pos2(padding_rect.max.x - 15.0, padding_rect.max.y - 15.0),
                );

                ui.painter().rect_filled(margin_rect, 0.0, margin_color);
                ui.painter().rect_filled(border_rect, 0.0, border_color);
                ui.painter().rect_filled(padding_rect, 0.0, padding_color);
                ui.painter().rect_filled(content_rect, 0.0, content_color);

                // 添加标签
                ui.painter().text(
                    egui::pos2(margin_rect.min.x + 5.0, margin_rect.min.y + 5.0),
                    egui::Align2::LEFT_TOP,
                    "外边距(margin)",
                    egui::FontId::proportional(14.0),
                    egui::Color32::BLACK,
                );
                ui.painter().text(
                    egui::pos2(border_rect.min.x + 5.0, border_rect.min.y + 5.0),
                    egui::Align2::LEFT_TOP,
                    "边框(border)",
                    egui::FontId::proportional(14.0),
                    egui::Color32::BLACK,
                );
                ui.painter().text(
                    egui::pos2(padding_rect.min.x + 5.0, padding_rect.min.y + 5.0),
                    egui::Align2::LEFT_TOP,
                    "内边距(padding)",
                    egui::FontId::proportional(14.0),
                    egui::Color32::BLACK,
                );
                ui.painter().text(
                    content_rect.center(),
                    egui::Align2::CENTER_CENTER,
                    "内容(content)",
                    egui::FontId::proportional(16.0),
                    egui::Color32::BLACK,
                );

                // 添加尺寸标签
                let dimensions = "宽: 200px, 高: 150px";
                ui.painter().text(
                    egui::pos2(content_rect.center().x, content_rect.center().y + 20.0),
                    egui::Align2::CENTER_CENTER,
                    dimensions,
                    egui::FontId::proportional(14.0),
                    egui::Color32::BLACK,
                );
            } else {
                ui.painter().text(
                    rect.center(),
                    egui::Align2::CENTER_CENTER,
                    "",
                    egui::FontId::default(),
                    egui::Color32::GRAY,
                );
            }
        });
    }

    // 弹性布局标签页
    pub fn render_flex_layout_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("弹性布局(Flexbox)测试");

        ui.add_space(10.0);
        ui.label("HTML内容:");
        ui.text_edit_multiline(&mut self.html_input);

        ui.add_space(5.0);
        ui.label("CSS样式:");
        ui.text_edit_multiline(&mut self.css_input);

        ui.add_space(10.0);
        ui.collapsing("Flex属性调整", |ui| {
            ui.horizontal(|ui| {
                ui.label("容器方向(flex-direction):");
                egui::ComboBox::from_id_source("flex_direction")
                    .selected_text(self.flex_direction.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(&mut self.flex_direction, "row".to_string(), "row");
                        ui.selectable_value(
                            &mut self.flex_direction,
                            "row-reverse".to_string(),
                            "row-reverse",
                        );
                        ui.selectable_value(
                            &mut self.flex_direction,
                            "column".to_string(),
                            "column",
                        );
                        ui.selectable_value(
                            &mut self.flex_direction,
                            "column-reverse".to_string(),
                            "column-reverse",
                        );
                    });
            });

            ui.horizontal(|ui| {
                ui.label("内容对齐(justify-content):");
                egui::ComboBox::from_id_source("justify_content")
                    .selected_text(self.justify_content.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(
                            &mut self.justify_content,
                            "flex-start".to_string(),
                            "flex-start",
                        );
                        ui.selectable_value(
                            &mut self.justify_content,
                            "flex-end".to_string(),
                            "flex-end",
                        );
                        ui.selectable_value(
                            &mut self.justify_content,
                            "center".to_string(),
                            "center",
                        );
                        ui.selectable_value(
                            &mut self.justify_content,
                            "space-between".to_string(),
                            "space-between",
                        );
                        ui.selectable_value(
                            &mut self.justify_content,
                            "space-around".to_string(),
                            "space-around",
                        );
                    });
            });

            ui.horizontal(|ui| {
                ui.label("项目对齐(align-items):");
                egui::ComboBox::from_id_source("align_items")
                    .selected_text(self.align_items.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(
                            &mut self.align_items,
                            "flex-start".to_string(),
                            "flex-start",
                        );
                        ui.selectable_value(
                            &mut self.align_items,
                            "flex-end".to_string(),
                            "flex-end",
                        );
                        ui.selectable_value(&mut self.align_items, "center".to_string(), "center");
                        ui.selectable_value(
                            &mut self.align_items,
                            "stretch".to_string(),
                            "stretch",
                        );
                        ui.selectable_value(
                            &mut self.align_items,
                            "baseline".to_string(),
                            "baseline",
                        );
                    });
            });

            ui.horizontal(|ui| {
                ui.label("换行(flex-wrap):");
                egui::ComboBox::from_id_source("flex_wrap")
                    .selected_text(self.flex_wrap.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(&mut self.flex_wrap, "nowrap".to_string(), "nowrap");
                        ui.selectable_value(&mut self.flex_wrap, "wrap".to_string(), "wrap");
                        ui.selectable_value(
                            &mut self.flex_wrap,
                            "wrap-reverse".to_string(),
                            "wrap-reverse",
                        );
                    });
            });
        });

        ui.add_space(10.0);
        if ui.button("应用Flex布局").clicked() {
            self.layout_result = self.generate_flex_layout_css();
            self.generate_flex_layout_preview();
        }

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("生成的CSS:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.layout_result)
                        .desired_width(ui.available_width() * 0.95)
                        .desired_rows(8)
                        .frame(true)
                        .interactive(false), // 修改 read_only(true) 为 interactive(false)
                );
            });

            ui.vertical(|ui| {
                ui.label("预览:");
                let (rect, _) = ui.allocate_exact_size(
                    egui::vec2(ui.available_width() * 0.95, 200.0),
                    egui::Sense::hover(),
                );

                // 绘制flex布局预览
                ui.painter()
                    .rect_filled(rect, 4.0, egui::Color32::from_rgb(240, 240, 240));

                // 这里我们简单模拟一些flex项目
                let container_padding = 10.0;
                let flex_container = egui::Rect::from_min_max(
                    egui::pos2(
                        rect.min.x + container_padding,
                        rect.min.y + container_padding,
                    ),
                    egui::pos2(
                        rect.max.x - container_padding,
                        rect.max.y - container_padding,
                    ),
                );

                ui.painter().rect_stroke(
                    flex_container,
                    2.0,
                    egui::Stroke::new(1.0, egui::Color32::DARK_GRAY),
                );

                // 根据flex属性排列项目
                let item_colors = [
                    egui::Color32::from_rgb(231, 76, 60),
                    egui::Color32::from_rgb(52, 152, 219),
                    egui::Color32::from_rgb(46, 204, 113),
                    egui::Color32::from_rgb(155, 89, 182),
                ];

                let item_width = 50.0;
                let item_height = 50.0;
                let item_margin = 5.0;

                let is_row = self.flex_direction.contains("row");
                let is_reverse = self.flex_direction.contains("reverse");

                let available_space = if is_row {
                    flex_container.width() - (item_width + item_margin * 2.0) * 4.0
                } else {
                    flex_container.height() - (item_height + item_margin * 2.0) * 4.0
                };

                for i in 0..4 {
                    let idx = if is_reverse { 3 - i } else { i };

                    let (x, y) = if is_row {
                        let justify_offset = match self.justify_content.as_str() {
                            "flex-start" => 0.0,
                            "flex-end" => available_space,
                            "center" => available_space / 2.0,
                            "space-between" => {
                                if i == 0 {
                                    0.0
                                } else {
                                    i as f32 * available_space / 3.0
                                }
                            }
                            "space-around" => (i as f32 + 0.5) * available_space / 4.0,
                            _ => 0.0,
                        };

                        let align_offset = match self.align_items.as_str() {
                            "flex-start" => 0.0,
                            "flex-end" => flex_container.height() - item_height,
                            "center" => (flex_container.height() - item_height) / 2.0,
                            "stretch" => 0.0, // 在实际情况下会拉伸，这里简化处理
                            _ => 0.0,
                        };

                        (
                            flex_container.min.x
                                + justify_offset
                                + idx as f32 * (item_width + item_margin * 2.0)
                                + item_margin,
                            flex_container.min.y + align_offset,
                        )
                    } else {
                        let justify_offset = match self.justify_content.as_str() {
                            "flex-start" => 0.0,
                            "flex-end" => available_space,
                            "center" => available_space / 2.0,
                            "space-between" => {
                                if i == 0 {
                                    0.0
                                } else {
                                    i as f32 * available_space / 3.0
                                }
                            }
                            "space-around" => (i as f32 + 0.5) * available_space / 4.0,
                            _ => 0.0,
                        };

                        let align_offset = match self.align_items.as_str() {
                            "flex-start" => 0.0,
                            "flex-end" => flex_container.width() - item_width,
                            "center" => (flex_container.width() - item_width) / 2.0,
                            "stretch" => 0.0,
                            _ => 0.0,
                        };

                        (
                            flex_container.min.x + align_offset,
                            flex_container.min.y
                                + justify_offset
                                + idx as f32 * (item_height + item_margin * 2.0)
                                + item_margin,
                        )
                    };

                    let item_rect = if self.align_items == "stretch" && is_row {
                        egui::Rect::from_min_size(
                            egui::pos2(x, flex_container.min.y),
                            egui::vec2(item_width, flex_container.height()),
                        )
                    } else if self.align_items == "stretch" && !is_row {
                        egui::Rect::from_min_size(
                            egui::pos2(flex_container.min.x, y),
                            egui::vec2(flex_container.width(), item_height),
                        )
                    } else {
                        egui::Rect::from_min_size(
                            egui::pos2(x, y),
                            egui::vec2(item_width, item_height),
                        )
                    };

                    ui.painter()
                        .rect_filled(item_rect, 4.0, item_colors[i % item_colors.len()]);

                    ui.painter().text(
                        item_rect.center(),
                        egui::Align2::CENTER_CENTER,
                        format!("{}", i + 1),
                        egui::FontId::proportional(16.0),
                        egui::Color32::WHITE,
                    );
                }
            });
        });
    }

    // 网格布局标签页
    pub fn render_grid_layout_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("网格布局(CSS Grid)测试");

        ui.add_space(10.0);
        ui.label("HTML内容:");
        ui.text_edit_multiline(&mut self.html_input);

        ui.add_space(5.0);
        ui.label("CSS样式:");
        ui.text_edit_multiline(&mut self.css_input);

        ui.add_space(10.0);
        ui.collapsing("Grid属性调整", |ui| {
            ui.horizontal(|ui| {
                ui.label("列模板(grid-template-columns):");
                ui.add(
                    egui::TextEdit::singleline(&mut self.grid_template_columns)
                        .desired_width(200.0),
                );
            });

            ui.horizontal(|ui| {
                ui.label("行模板(grid-template-rows):");
                ui.add(
                    egui::TextEdit::singleline(&mut self.grid_template_rows).desired_width(200.0),
                );
            });

            ui.horizontal(|ui| {
                ui.label("列间距(column-gap):");
                ui.add(egui::Slider::new(&mut self.grid_column_gap, 0..=50).text("px"));
            });

            ui.horizontal(|ui| {
                ui.label("行间距(row-gap):");
                ui.add(egui::Slider::new(&mut self.grid_row_gap, 0..=50).text("px"));
            });

            ui.horizontal(|ui| {
                ui.label("对齐内容(justify-content):");
                egui::ComboBox::from_id_source("grid_justify_content")
                    .selected_text(self.grid_justify_content.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(
                            &mut self.grid_justify_content,
                            "start".to_string(),
                            "start",
                        );
                        ui.selectable_value(
                            &mut self.grid_justify_content,
                            "end".to_string(),
                            "end",
                        );
                        ui.selectable_value(
                            &mut self.grid_justify_content,
                            "center".to_string(),
                            "center",
                        );
                        ui.selectable_value(
                            &mut self.grid_justify_content,
                            "space-between".to_string(),
                            "space-between",
                        );
                        ui.selectable_value(
                            &mut self.grid_justify_content,
                            "space-around".to_string(),
                            "space-around",
                        );
                    });
            });

            ui.horizontal(|ui| {
                ui.label("对齐项目(align-items):");
                egui::ComboBox::from_id_source("grid_align_items")
                    .selected_text(self.grid_align_items.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(
                            &mut self.grid_align_items,
                            "start".to_string(),
                            "start",
                        );
                        ui.selectable_value(&mut self.grid_align_items, "end".to_string(), "end");
                        ui.selectable_value(
                            &mut self.grid_align_items,
                            "center".to_string(),
                            "center",
                        );
                        ui.selectable_value(
                            &mut self.grid_align_items,
                            "stretch".to_string(),
                            "stretch",
                        );
                    });
            });
        });

        ui.add_space(10.0);
        if ui.button("应用Grid布局").clicked() {
            self.layout_result = self.generate_grid_layout_css();
            self.generate_grid_layout_preview();
        }

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("生成的CSS:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.layout_result)
                        .desired_width(ui.available_width() * 0.95)
                        .desired_rows(8)
                        .frame(true)
                        .interactive(false), // 修改 read_only(true) 为 interactive(false)
                );
            });

            ui.vertical(|ui| {
                ui.label("预览:");
                let (rect, _) = ui.allocate_exact_size(
                    egui::vec2(ui.available_width() * 0.95, 300.0),
                    egui::Sense::hover(),
                );

                // 绘制grid布局预览
                ui.painter()
                    .rect_filled(rect, 4.0, egui::Color32::from_rgb(240, 240, 240));

                // 这里我们简单模拟一个3x3的网格
                let container_padding = 10.0;
                let grid_container = egui::Rect::from_min_max(
                    egui::pos2(
                        rect.min.x + container_padding,
                        rect.min.y + container_padding,
                    ),
                    egui::pos2(
                        rect.max.x - container_padding,
                        rect.max.y - container_padding,
                    ),
                );

                ui.painter().rect_stroke(
                    grid_container,
                    2.0,
                    egui::Stroke::new(1.0, egui::Color32::DARK_GRAY),
                );

                let cols = 3;
                let rows = 3;
                let col_gap = self.grid_column_gap as f32;
                let row_gap = self.grid_row_gap as f32;

                let available_width = grid_container.width() - col_gap * (cols as f32 - 1.0);
                let available_height = grid_container.height() - row_gap * (rows as f32 - 1.0);

                let cell_width = available_width / cols as f32;
                let cell_height = available_height / rows as f32;

                let item_colors = [
                    egui::Color32::from_rgb(231, 76, 60),
                    egui::Color32::from_rgb(52, 152, 219),
                    egui::Color32::from_rgb(46, 204, 113),
                    egui::Color32::from_rgb(155, 89, 182),
                    egui::Color32::from_rgb(241, 196, 15),
                    egui::Color32::from_rgb(230, 126, 34),
                    egui::Color32::from_rgb(149, 165, 166),
                    egui::Color32::from_rgb(41, 128, 185),
                    egui::Color32::from_rgb(211, 84, 0),
                ];

                for row in 0..rows {
                    for col in 0..cols {
                        let idx = row * cols + col;

                        let x = grid_container.min.x + col as f32 * (cell_width + col_gap);
                        let y = grid_container.min.y + row as f32 * (cell_height + row_gap);

                        let cell_rect = egui::Rect::from_min_size(
                            egui::pos2(x, y),
                            egui::vec2(cell_width, cell_height),
                        );

                        ui.painter().rect_filled(
                            cell_rect,
                            4.0,
                            item_colors[idx % item_colors.len()],
                        );

                        ui.painter().text(
                            cell_rect.center(),
                            egui::Align2::CENTER_CENTER,
                            format!("{}", idx + 1),
                            egui::FontId::proportional(16.0),
                            egui::Color32::WHITE,
                        );
                    }
                }

                // 绘制网格线
                for i in 0..=cols {
                    let x = grid_container.min.x + i as f32 * (cell_width + col_gap);
                    if i < cols {
                        ui.painter().line_segment(
                            [
                                egui::pos2(x + cell_width + col_gap / 2.0, grid_container.min.y),
                                egui::pos2(x + cell_width + col_gap / 2.0, grid_container.max.y),
                            ],
                            egui::Stroke::new(1.0, egui::Color32::GRAY),
                        );
                    }
                }

                for i in 0..=rows {
                    let y = grid_container.min.y + i as f32 * (cell_height + row_gap);
                    if i < rows {
                        ui.painter().line_segment(
                            [
                                egui::pos2(grid_container.min.x, y + cell_height + row_gap / 2.0),
                                egui::pos2(grid_container.max.x, y + cell_height + row_gap / 2.0),
                            ],
                            egui::Stroke::new(1.0, egui::Color32::GRAY),
                        );
                    }
                }
            });
        });
    }

    // 定位系统标签页
    pub fn render_positioning_tab(&mut self, ui: &mut egui::Ui) {
        ui.heading("CSS定位系统");

        ui.add_space(10.0);
        ui.label("HTML内容:");
        ui.text_edit_multiline(&mut self.html_input);

        ui.add_space(5.0);
        ui.label("CSS样式:");
        ui.text_edit_multiline(&mut self.css_input);

        ui.add_space(10.0);
        ui.collapsing("定位属性", |ui| {
            ui.horizontal(|ui| {
                ui.label("定位类型(position):");
                egui::ComboBox::from_id_source("position_type")
                    .selected_text(self.position_type.clone())
                    .show_ui(ui, |ui| {
                        ui.selectable_value(
                            &mut self.position_type,
                            "static".to_string(),
                            "static",
                        );
                        ui.selectable_value(
                            &mut self.position_type,
                            "relative".to_string(),
                            "relative",
                        );
                        ui.selectable_value(
                            &mut self.position_type,
                            "absolute".to_string(),
                            "absolute",
                        );
                        ui.selectable_value(&mut self.position_type, "fixed".to_string(), "fixed");
                        ui.selectable_value(
                            &mut self.position_type,
                            "sticky".to_string(),
                            "sticky",
                        );
                    });
            });

            ui.horizontal(|ui| {
                ui.label("顶部偏移(top):");
                ui.add(egui::Slider::new(&mut self.position_top, -100..=100).text("px"));
            });

            ui.horizontal(|ui| {
                ui.label("左侧偏移(left):");
                ui.add(egui::Slider::new(&mut self.position_left, -100..=100).text("px"));
            });

            ui.horizontal(|ui| {
                ui.label("堆叠顺序(z-index):");
                ui.add(egui::Slider::new(&mut self.z_index, 0..=10));
            });

            ui.checkbox(&mut self.use_transform, "使用变换 (transform)");

            if self.use_transform {
                ui.horizontal(|ui| {
                    ui.label("旋转(rotate):");
                    ui.add(egui::Slider::new(&mut self.transform_rotate, 0..=360).text("deg"));
                });

                ui.horizontal(|ui| {
                    ui.label("缩放(scale):");
                    ui.add(egui::Slider::new(&mut self.transform_scale, 0.5..=2.0).step_by(0.1));
                });
            }
        });

        ui.add_space(10.0);
        if ui.button("应用定位").clicked() {
            self.layout_result = self.generate_positioning_css();
        }

        ui.add_space(10.0);
        ui.horizontal(|ui| {
            ui.vertical(|ui| {
                ui.label("生成的CSS:");
                ui.add(
                    egui::TextEdit::multiline(&mut self.layout_result)
                        .desired_width(ui.available_width() * 0.95)
                        .desired_rows(8)
                        .frame(true)
                        .interactive(false), // 修改 read_only(true) 为 interactive(false)
                );
            });

            ui.vertical(|ui| {
                ui.label("预览:");
                let (rect, _) = ui.allocate_exact_size(
                    egui::vec2(ui.available_width() * 0.95, 300.0),
                    egui::Sense::hover(),
                );

                // 绘制定位预览
                ui.painter()
                    .rect_filled(rect, 4.0, egui::Color32::from_rgb(240, 240, 240));

                // 绘制一个容器
                let container_padding = 10.0;
                let container = egui::Rect::from_min_max(
                    egui::pos2(
                        rect.min.x + container_padding,
                        rect.min.y + container_padding,
                    ),
                    egui::pos2(
                        rect.max.x - container_padding,
                        rect.max.y - container_padding,
                    ),
                );

                ui.painter().rect_stroke(
                    container,
                    2.0,
                    egui::Stroke::new(1.0, egui::Color32::DARK_GRAY),
                );

                // 绘制定位元素
                let base_x = container.min.x + container.width() / 2.0;
                let base_y = container.min.y + container.height() / 2.0;

                let element_width = 100.0;
                let element_height = 100.0;

                let pos = match self.position_type.as_str() {
                    "static" => {
                        egui::pos2(base_x - element_width / 2.0, base_y - element_height / 2.0)
                    }
                    "relative" => egui::pos2(
                        base_x - element_width / 2.0 + self.position_left as f32,
                        base_y - element_height / 2.0 + self.position_top as f32,
                    ),
                    "absolute" | "fixed" => egui::pos2(
                        container.min.x + self.position_left as f32,
                        container.min.y + self.position_top as f32,
                    ),
                    "sticky" => {
                        // 简化模拟sticky
                        let sticky_pos_y = (container.min.y + 20.0)
                            .max(container.min.y + self.position_top as f32);
                        egui::pos2(base_x - element_width / 2.0, sticky_pos_y)
                    }
                    _ => egui::pos2(base_x - element_width / 2.0, base_y - element_height / 2.0),
                };

                let element_rect =
                    egui::Rect::from_min_size(pos, egui::vec2(element_width, element_height));

                // 应用变换
                if self.use_transform {
                    ui.painter().rect_filled(
                        element_rect,
                        4.0,
                        egui::Color32::from_rgb(52, 152, 219),
                    );

                    // 为了显示变换效果，我们绘制一个旋转的框
                    let center = element_rect.center();
                    let angle = (self.transform_rotate as f32) * std::f32::consts::PI / 180.0;
                    let scale = self.transform_scale;

                    let corners = [
                        egui::vec2(-element_width / 2.0, -element_height / 2.0),
                        egui::vec2(element_width / 2.0, -element_height / 2.0),
                        egui::vec2(element_width / 2.0, element_height / 2.0),
                        egui::vec2(-element_width / 2.0, element_height / 2.0),
                    ];

                    let transformed_corners: Vec<egui::Pos2> = corners
                        .iter()
                        .map(|corner| {
                            let x = corner.x * scale * angle.cos() - corner.y * scale * angle.sin();
                            let y = corner.x * scale * angle.sin() + corner.y * scale * angle.cos();
                            egui::pos2(center.x + x, center.y + y)
                        })
                        .collect();

                    for i in 0..4 {
                        ui.painter().line_segment(
                            [transformed_corners[i], transformed_corners[(i + 1) % 4]],
                            egui::Stroke::new(2.0, egui::Color32::from_rgb(231, 76, 60)),
                        );
                    }

                    ui.painter().text(
                        center,
                        egui::Align2::CENTER_CENTER,
                        format!(
                            "transform\nrotate({}deg)\nscale({})",
                            self.transform_rotate, self.transform_scale
                        ),
                        egui::FontId::proportional(14.0),
                        egui::Color32::WHITE,
                    );
                } else {
                    ui.painter().rect_filled(
                        element_rect,
                        4.0,
                        egui::Color32::from_rgb(52, 152, 219),
                    );

                    ui.painter().text(
                        element_rect.center(),
                        egui::Align2::CENTER_CENTER,
                        format!(
                            "position: {}\nz-index: {}\ntop: {}px\nleft: {}px",
                            self.position_type, self.z_index, self.position_top, self.position_left
                        ),
                        egui::FontId::proportional(14.0),
                        egui::Color32::WHITE,
                    );
                }

                // 添加标记
                ui.painter().text(
                    egui::pos2(container.min.x + 10.0, container.min.y + 10.0),
                    egui::Align2::LEFT_TOP,
                    "容器",
                    egui::FontId::proportional(14.0),
                    egui::Color32::BLACK,
                );
            });
        });
    }

    // 布局引擎辅助方法
    fn analyze_box_model(&self) -> String {
        let mut result = String::new();

        if self.css_selector.is_empty() {
            return "请输入要分析的CSS选择器".to_string();
        }

        result.push_str(&format!(
            "选择器 \"{}\" 的盒模型分析:\n\n",
            self.css_selector
        ));

        // 解析CSS并提取盒模型相关属性
        let mut box_model = BoxModelProperties {
            width: "auto".to_string(),
            height: "auto".to_string(),
            padding_top: "0px".to_string(),
            padding_right: "0px".to_string(),
            padding_bottom: "0px".to_string(),
            padding_left: "0px".to_string(),
            border_top_width: "0px".to_string(),
            border_right_width: "0px".to_string(),
            border_bottom_width: "0px".to_string(),
            border_left_width: "0px".to_string(),
            margin_top: "0px".to_string(),
            margin_right: "0px".to_string(),
            margin_bottom: "0px".to_string(),
            margin_left: "0px".to_string(),
            box_sizing: "content-box".to_string(),
        };

        // 提取CSS中的盒模型属性（简化实现）
        for line in self.css_input.lines() {
            let line = line.trim();

            if line.is_empty() || !line.contains(":") {
                continue;
            }

            let parts: Vec<&str> = line.split(':').collect();
            if parts.len() < 2 {
                continue;
            }

            let property = parts[0].trim();
            let value = parts[1].trim().trim_end_matches(';').trim();

            match property {
                "width" => box_model.width = value.to_string(),
                "height" => box_model.height = value.to_string(),
                "padding" => {
                    box_model.padding_top = value.to_string();
                    box_model.padding_right = value.to_string();
                    box_model.padding_bottom = value.to_string();
                    box_model.padding_left = value.to_string();
                }
                "padding-top" => box_model.padding_top = value.to_string(),
                "padding-right" => box_model.padding_right = value.to_string(),
                "padding-bottom" => box_model.padding_bottom = value.to_string(),
                "padding-left" => box_model.padding_left = value.to_string(),
                "border-width" => {
                    box_model.border_top_width = value.to_string();
                    box_model.border_right_width = value.to_string();
                    box_model.border_bottom_width = value.to_string();
                    box_model.border_left_width = value.to_string();
                }
                "border-top-width" => box_model.border_top_width = value.to_string(),
                "border-right-width" => box_model.border_right_width = value.to_string(),
                "border-bottom-width" => box_model.border_bottom_width = value.to_string(),
                "border-left-width" => box_model.border_left_width = value.to_string(),
                "margin" => {
                    box_model.margin_top = value.to_string();
                    box_model.margin_right = value.to_string();
                    box_model.margin_bottom = value.to_string();
                    box_model.margin_left = value.to_string();
                }
                "margin-top" => box_model.margin_top = value.to_string(),
                "margin-right" => box_model.margin_right = value.to_string(),
                "margin-bottom" => box_model.margin_bottom = value.to_string(),
                "margin-left" => box_model.margin_left = value.to_string(),
                "box-sizing" => box_model.box_sizing = value.to_string(),
                _ => {}
            }
        }

        // 格式化结果
        result.push_str("┌──────────────────────────────────────────────\n");
        result.push_str("│ 盒模型属性:\n");
        result.push_str(&format!("│ ├── 宽度: {}\n", box_model.width));
        result.push_str(&format!("│ ├── 高度: {}\n", box_model.height));
        result.push_str(&format!("│ ├── 盒模型类型: {}\n", box_model.box_sizing));
        result.push_str("│ ├── 内边距:\n");
        result.push_str(&format!("│ │   ├── 上: {}\n", box_model.padding_top));
        result.push_str(&format!("│ │   ├── 右: {}\n", box_model.padding_right));
        result.push_str(&format!("│ │   ├── 下: {}\n", box_model.padding_bottom));
        result.push_str(&format!("│ │   └── 左: {}\n", box_model.padding_left));
        result.push_str("│ ├── 边框宽度:\n");
        result.push_str(&format!("│ │   ├── 上: {}\n", box_model.border_top_width));
        result.push_str(&format!("│ │   ├── 右: {}\n", box_model.border_right_width));
        result.push_str(&format!(
            "│ │   ├── 下: {}\n",
            box_model.border_bottom_width
        ));
        result.push_str(&format!("│ │   └── 左: {}\n", box_model.border_left_width));
        result.push_str("│ └── 外边距:\n");
        result.push_str(&format!("│     ├── 上: {}\n", box_model.margin_top));
        result.push_str(&format!("│     ├── 右: {}\n", box_model.margin_right));
        result.push_str(&format!("│     ├── 下: {}\n", box_model.margin_bottom));
        result.push_str(&format!("│     └── 左: {}\n", box_model.margin_left));
        result.push_str("└──────────────────────────────────────────────\n\n");

        // 计算总宽度和高度（简化计算）
        let content_width = if box_model.width == "auto" {
            "auto".to_string()
        } else {
            "200px".to_string() // 假设为200px
        };

        let content_height = if box_model.height == "auto" {
            "auto".to_string()
        } else {
            "150px".to_string() // 假设为150px
        };

        // 提取数值，简化处理
        let padding_left = 10; // 简化，假设值为10px
        let padding_right = 10;
        let padding_top = 10;
        let padding_bottom = 10;

        let border_left = 1; // 简化，假设值为1px
        let border_right = 1;
        let border_top = 1;
        let border_bottom = 1;

        let margin_left = 20; // 简化，假设值为20px
        let margin_right = 20;
        let margin_top = 20;
        let margin_bottom = 20;

        // 总宽度和高度计算
        let total_width = 200 + padding_left + padding_right + border_left + border_right;
        let total_height = 150 + padding_top + padding_bottom + border_top + border_bottom;

        // 占用的空间
        let occupied_width = total_width + margin_left + margin_right;
        let occupied_height = total_height + margin_top + margin_bottom;

        result.push_str("盒模型计算:\n");
        result.push_str(&format!(
            "内容区域: 宽 {} x 高 {}\n",
            content_width, content_height
        ));
        result.push_str(&format!(
            "内容区域 + 内边距 + 边框: 宽 {}px x 高 {}px\n",
            total_width, total_height
        ));
        result.push_str(&format!(
            "占用空间 (含外边距): 宽 {}px x 高 {}px\n",
            occupied_width, occupied_height
        ));

        if box_model.box_sizing == "border-box" {
            result.push_str("\n注意: 由于使用了 box-sizing: border-box，内容区域的实际大小会小于设定的宽高值，因为内边距和边框会计入宽高。\n");
        }

        result
    }

    // 生成弹性布局的CSS
    fn generate_flex_layout_css(&self) -> String {
        let mut css = String::new();

        css.push_str(".container {\n");
        css.push_str("    display: flex;\n");
        css.push_str(&format!("    flex-direction: {};\n", self.flex_direction));
        css.push_str(&format!("    justify-content: {};\n", self.justify_content));
        css.push_str(&format!("    align-items: {};\n", self.align_items));
        css.push_str(&format!("    flex-wrap: {};\n", self.flex_wrap));
        css.push_str("    width: 100%;\n");
        css.push_str("    height: 300px;\n");
        css.push_str("    border: 1px solid #ccc;\n");
        css.push_str("    padding: 10px;\n");
        css.push_str("}\n\n");

        css.push_str(".item {\n");
        css.push_str("    width: 50px;\n");
        css.push_str("    height: 50px;\n");
        css.push_str("    margin: 5px;\n");
        css.push_str("    display: flex;\n");
        css.push_str("    justify-content: center;\n");
        css.push_str("    align-items: center;\n");
        css.push_str("    color: white;\n");
        css.push_str("    font-weight: bold;\n");
        css.push_str("}\n\n");

        css.push_str(".item:nth-child(1) { background-color: #e74c3c; }\n");
        css.push_str(".item:nth-child(2) { background-color: #3498db; }\n");
        css.push_str(".item:nth-child(3) { background-color: #2ecc71; }\n");
        css.push_str(".item:nth-child(4) { background-color: #9b59b6; }\n");

        css
    }

    // 生成网格布局的CSS
    fn generate_grid_layout_css(&self) -> String {
        let mut css = String::new();

        css.push_str(".container {\n");
        css.push_str("    display: grid;\n");
        css.push_str(&format!(
            "    grid-template-columns: {};\n",
            self.grid_template_columns
        ));
        css.push_str(&format!(
            "    grid-template-rows: {};\n",
            self.grid_template_rows
        ));
        css.push_str(&format!("    column-gap: {}px;\n", self.grid_column_gap));
        css.push_str(&format!("    row-gap: {}px;\n", self.grid_row_gap));
        css.push_str(&format!(
            "    justify-content: {};\n",
            self.grid_justify_content
        ));
        css.push_str(&format!("    align-items: {};\n", self.grid_align_items));
        css.push_str("    width: 100%;\n");
        css.push_str("    height: 300px;\n");
        css.push_str("    border: 1px solid #ccc;\n");
        css.push_str("    padding: 10px;\n");
        css.push_str("}\n\n");

        css.push_str(".item {\n");
        css.push_str("    display: flex;\n");
        css.push_str("    justify-content: center;\n");
        css.push_str("    align-items: center;\n");
        css.push_str("    color: white;\n");
        css.push_str("    font-weight: bold;\n");
        css.push_str("}\n\n");

        // 为9个项目定义样式
        for i in 1..=9 {
            css.push_str(&format!(
                ".item:nth-child({}) {{ background-color: {}; }}\n",
                i,
                match i % 9 {
                    1 => "#e74c3c",
                    2 => "#3498db",
                    3 => "#2ecc71",
                    4 => "#9b59b6",
                    5 => "#f1c40f",
                    6 => "#e67e22",
                    7 => "#95a5a6",
                    8 => "#2980b9",
                    _ => "#d35400",
                }
            ));
        }

        css
    }

    // 生成定位CSS
    fn generate_positioning_css(&self) -> String {
        let mut css = String::new();

        css.push_str(".container {\n");
        css.push_str("    position: relative;\n");
        css.push_str("    width: 100%;\n");
        css.push_str("    height: 300px;\n");
        css.push_str("    border: 1px solid #ccc;\n");
        css.push_str("    background-color: #f0f0f0;\n");
        css.push_str("}\n\n");

        css.push_str(".element {\n");
        css.push_str(&format!("    position: {};\n", self.position_type));

        if self.position_type != "static" {
            css.push_str(&format!("    top: {}px;\n", self.position_top));
            css.push_str(&format!("    left: {}px;\n", self.position_left));
            css.push_str(&format!("    z-index: {};\n", self.z_index));
        }

        if self.use_transform {
            css.push_str(&format!(
                "    transform: rotate({}deg) scale({});\n",
                self.transform_rotate, self.transform_scale
            ));
        }

        css.push_str("    width: 100px;\n");
        css.push_str("    height: 100px;\n");
        css.push_str("    background-color: #3498db;\n");
        css.push_str("    color: white;\n");
        css.push_str("    display: flex;\n");
        css.push_str("    justify-content: center;\n");
        css.push_str("    align-items: center;\n");
        css.push_str("    text-align: center;\n");
        css.push_str("}\n");

        css
    }

    // 生成弹性布局预览
    fn generate_flex_layout_preview(&mut self) {
        // 在实际项目中，这里可能会生成HTML预览或其他可视化输出
    }

    // 生成网格布局预览
    fn generate_grid_layout_preview(&mut self) {
        // 在实际项目中，这里可能会生成HTML预览或其他可视化输出
    }
}

// 定义盒模型属性结构
struct BoxModelProperties {
    width: String,
    height: String,
    padding_top: String,
    padding_right: String,
    padding_bottom: String,
    padding_left: String,
    border_top_width: String,
    border_right_width: String,
    border_bottom_width: String,
    border_left_width: String,
    margin_top: String,
    margin_right: String,
    margin_bottom: String,
    margin_left: String,
    box_sizing: String,
}
